package com.jack.payment.service.strategy.impl;


import com.jack.payment.dao.config.ConfigPayStripeDao;
import com.jack.payment.entity.business.ApplyRefundBo;
import com.jack.payment.entity.business.RequestPayBo;
import com.jack.payment.entity.common.BusinessException;
import com.jack.payment.entity.generate.config.ConfigPayStripeModel;
import com.jack.payment.entity.result.ResultPayVo;
import com.jack.payment.service.strategy.PaymentStrategy;
import com.jack.payment.util.auth.DataAuthUtils;
import com.stripe.exception.StripeException;
import com.stripe.model.PaymentIntent;
import com.stripe.net.RequestOptions;
import com.stripe.param.PaymentIntentCreateParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service("CardPay")
public class StripePaymentService implements PaymentStrategy {
    private Logger log = LoggerFactory.getLogger(StripePaymentService.class);

    private volatile RequestOptions requestOptions;
    private static final BigDecimal ONEHUNDRED = new BigDecimal("100");
    // stripe 支持的支付方式:  alipay,  wechat_pay, paypal
    private static final String[] STRIPEMETHOD = {"card"};
    // stripe 基础配置信息
    private ConfigPayStripeModel configStripeData;

    @Autowired
    private ConfigPayStripeDao configPayStripeDao;
    @Autowired
    private DataAuthUtils dataAuthUtils;


    @Override
    public synchronized void updatePaymentMethodConfig(Integer id) throws BusinessException {
        configStripeData =
                dataAuthUtils.decodeConfigStripe(configPayStripeDao.getAppointConfigStripe(id));
        requestOptions = RequestOptions.builder()
                .setApiKey(configStripeData.getSkKey())
                .build();
    }

    @Override
    public ResultPayVo createPaymentInfo(RequestPayBo requestPayBo) throws StripeException {
        Map<String, String> attach = new HashMap<>();
        attach.put("attach", requestPayBo.getOrderNo());
        Long thisPayAmount = requestPayBo.getAmount().multiply(ONEHUNDRED).longValue();
        // 构建stripe 支付
        PaymentIntentCreateParams params =
                PaymentIntentCreateParams.builder()
                        .addAllPaymentMethodType(Arrays.asList(STRIPEMETHOD))
                        .putAllMetadata(attach)
                        .setAmount(thisPayAmount)
                        .setCurrency("usd")
                        .build();
        PaymentIntent paymentIntent = PaymentIntent.create(params, requestOptions);
        return new ResultPayVo().builder()
                .paymentSignature(paymentIntent.getClientSecret())
                .paymentAmount(requestPayBo.getAmount())
                .orderNo(requestPayBo.getOrderNo())
                .nonceStr(configStripeData.getPkKey())
                .build();
    }

}
